package com.jy.event.service.impl;

import com.jy.event.dao.ElectronicBillDao;
import com.jy.event.dao.PaymentDao;
import com.jy.event.domain.ElectronicBill;
import com.jy.event.service.ElectronicBillService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by lihu on 2017/12/18.
 */
@Slf4j
@Service
public class ElectronicBillServiceImpl implements ElectronicBillService {


    private final static String URL = "APIGATEWAYURL/v1/system/notice";


    @Value("${api.gateway.url}")
    private String apiGatewayUrl;

    @Autowired
    ElectronicBillDao electronicBillDao;


    @Autowired
    PaymentDao paymentDao;

    @Autowired
    RestTemplate restTemplate;


    @Override
    @Transactional
    public void saveChack(ElectronicBill electronicBill, String storeName) {
        ElectronicBill electronicBill1 = electronicBillDao.findByMchIdAndStoreIdAndDateAndPayChannel(
                electronicBill.getMchId(), electronicBill.getStoreId(), electronicBill.getDate(), electronicBill.getPayChannel());
        if (electronicBill1 == null) {
            electronicBillDao.save(electronicBill);
        }
        //校验本地数据与第三方数据对比值
        checkAmunt(electronicBill, storeName);

    }

    private void checkAmunt(ElectronicBill electronicBill, String storeName) {
        try {
            ZoneId america = ZoneId.of("Asia/Shanghai");
            LocalDateTime localtDateAndTime = LocalDate.now().
                    atTime(0, 0, 0, 0);
            ZonedDateTime dateAndTimeInNewYork = ZonedDateTime.of(localtDateAndTime, america);

            Object amount = paymentDao.getThirdParty(electronicBill.getStoreId(),
                    Date.from(dateAndTimeInNewYork.toInstant()),
                    Date.from(dateAndTimeInNewYork.plusDays(1).toInstant()));
            int totalAmount = (int) Math.rint(Double.parseDouble(amount.toString()) * 100);
            if (electronicBill.getTotalAmountIncome() != totalAmount) {
                Map<String, Object> map = new HashMap<>();
                map.put("title", "第三方金额有误！");
                map.put("notice", "店铺ID" + electronicBill.getStoreId() + " ==" +
                        storeName + "\n 第三方金额:" + electronicBill.getTotalAmount() + "\n 查询金额:" + totalAmount);
                restTemplate.postForEntity(URL.replace("APIGATEWAYURL", apiGatewayUrl), map, String.class);
            }
        } catch (Exception ex) {
            log.error("checkAmunt is error==>electronicBill:{}", electronicBill, ex);
        }
    }


}
